# -*- coding: utf-8 -*-
from hashlib import md5
from datetime import datetime
from app import app, lm, db
from flask import render_template, url_for, redirect, flash, g, request, jsonify, make_response
from forms import LoginForm, NoteForm
from models import User, Note, NoteReview
from flask.ext.login import login_required, current_user, login_user, logout_user
import json, datetime

__author__ = 'nibo'

date_fmt = '%Y-%m-%d %H:%M:%S'

@lm.user_loader
def load_user(uid):
    return User.query.get(int(uid))


@app.before_request
def defore_request():
    g.user = current_user


@app.route('/index/')
@app.route('/')
@login_required
def index():
    return render_template('index.html')


@app.route('/setting/')
@login_required
def setting():
    return render_template('setting.html')


@app.route('/login/', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data,
                                    password=md5(form.email.data + form.password.data)
                                    .hexdigest()).first()
        if user is None:
            flash(u'用户名或密码错误')
            return render_template('login.html', form=form)
        login_user(user, form.remember_me.data)
        return redirect(request.args.get('next') or url_for('index'))
    # 用户已登录直接跳转到下一个页面或者首页
    if g.user.is_authenticated():
        return redirect(request.args.get('next') or url_for('index'))
    return render_template('login.html', form=form)


@app.route('/logout/')
def logout():
    logout_user()
    return redirect(url_for('login'))


@app.route('/note/', methods=['GET'])
def note():
    list_data = [
        {
            "id": "1",
            "title": u"测试1",
            "start": "2015-07-1 9:11:30",
            "end": "1970-01-01",
            "allDay": False,
            "color": None
        },
        {
            "id": "2",
            "title": u"测试asd顶替顶2",
            "start": "2015-07-10 18:00:00",
            "end": "1970-01-01 22:00:00",
            "allDay": False,
            "color": None
        },
        {
            "id": "3",
            "title": u"测试asd顶替顶3",
            "start": "2015-07-10 18:00:00",
            "end": "1970-01-01 22:00:00",
            "allDay": False,
            "color": None
        },
        {
            "id": "4",
            "title": u"测试asd顶替顶4",
            "start": "2015-07-10 18:00:00",
            "end": "1970-01-01 22:00:00",
            "allDay": False,
            "color": None
        },
        {
            "id": "5",
            "title": u"测试asd顶替顶5",
            "start": "2015-07-10 18:00:00",
            "end": "1970-01-01 22:00:00",
            "allDay": False,
            "color": None
        },
        {
            "id": "6",
            "title": u"测试asd顶替顶6",
            "start": "2015-07-10 18:00:00",
            "end": "1970-01-01 22:00:00",
            "allDay": False,
            "color": None
        },
        {
            "id": "7",
            "title": u"测试asd顶替顶7",
            "start": "2015-07-10 18:00:00",
            "end": "1970-01-01 22:00:00",
            "allDay": False,
            "color": None
        },
        {
            "id": "8",
            "title": u"测试asd顶替顶8",
            "start": "2015-07-10 18:00:00",
            "end": "1970-01-01 22:00:00",
            "allDay": False,
            "color": None
        },
        {
            "id": "9",
            "title": u"测试asd顶替顶7",
            "start": "2015-07-10 18:00:00",
            "end": "1970-01-01 22:00:00",
            "allDay": False,
            "color": None
        },
        {
            "id": "10",
            "title": u"测试asd顶替顶10",
            "start": "2015-07-10 18:00:00",
            "end": "1970-01-01 22:00:00",
            "allDay": False,
            "color": None
        },
        {
            "id": "11",
            "title": u"测试asd顶替顶11",
            "start": "2015-07-10 18:00:00",
            "end": "1970-01-01 22:00:00",
            "allDay": False,
            "color": None
        }
    ]

    print Note.query.filter_by(user_id=g.user.id).first()

    return json.dumps(list_data)


@app.route('/note/add/<date>', methods=['GET', 'POST'])
@login_required
def note_add(date):
    """
    记录添加请求
    :param date:
    :return:
    """
    form = NoteForm()
    if form.date.data is '':
        form.date.data = date
    if form.validate_on_submit():
        str_datetime = form.date.data + ' ' + datetime.datetime.now().strftime('%H:%M:%S')
        n = Note(content=form.content.data, remark=form.remark.data,
                 timestamp=datetime.datetime.now(),
                 note_time=datetime.datetime.strptime(str_datetime, date_fmt),
                 author=g.user)
        db.session.add(n)
        db.session.commit()
        flash(u'添加记录成功！')
        return redirect(url_for('index'))

    return render_template('note_add.html', form=form)


@app.route('/test/')
@login_required
def test():
    a = request.args.get('a', 0, type=int)
    b = request.args.get('b', 0, type=int)
    return jsonify(result=a + b)


@lm.unauthorized_handler
def unauthorized():
    headers = request.headers
    if 'X-Requested-With' in headers:
        return make_response(jsonify({'error': u'请先登录'}), 403)
    flash(u'请先登录')
    return make_response(redirect(url_for('login', next=request.path)))


@app.errorhandler(404)
def page_not_found(error):
    return render_template('404.html'), 404
